package pb

import (
	"fmt"
	"strings"
	"time"

	"gitee.com/xuender/monitor"
	"github.com/xuender/oils/base"
)

func (p *Stat) Startup() time.Time {
	return time.Unix(p.Btime, 0)
}

func (p *Stat) Report() string {
	return monitor.Printer.Sprintf(
		"report_head_%d_%v_%d_%d_%d_%d",
		len(p.Cpus),
		p.Startup(),
		p.Ctxt,
		p.Processes,
		p.ProcsRunning,
		p.ProcsBlocked,
	) +
		p.getIntrs() +
		p.getSoftirq() +
		p.getCPU()
}

func (p *Stat) getCPU() string {
	cpus := make([]string, len(p.Cpus)+base.Two)
	cpus[0] = monitor.Printer.Sprintf("cpu_head")
	cpus[1] = p.Cpu.Report(monitor.Printer.Sprintf("sum"))

	for index, cpu := range p.Cpus {
		cpus[index+2] = cpu.Report(fmt.Sprintf("CPU%d", index))
	}

	return "\n\n" + strings.Join(cpus, "\n")
}

func (p *Stat) getIntrs() string {
	intrs := []string{monitor.Printer.Sprintf("intr_head")}
	interrupts, _ := NewInterrupts()

	for index, intr := range p.Intr {
		name := monitor.Printer.Sprintf("sum")
		des := ""

		if intr > 0 {
			for _, inte := range interrupts {
				if base.Itoa(index-1) == inte.Name {
					name = base.Itoa(index - 1)
					des = inte.Description
				}
			}

			intrs = append(intrs, monitor.Printer.Sprintf("%s\t%10d\t%s", name, intr, des))
		}
	}

	return "\n" + strings.Join(intrs, "\n")
}

func (p *Stat) getSoftirq() string {
	softs := make([]string, len(p.Softirq)+1)
	softs[0] = monitor.Printer.Sprintf("soft_head")

	for index, soft := range p.Softirq {
		if index == 0 {
			softs[index+1] = monitor.Printer.Sprintf("%8s\t%d", monitor.Printer.Sprintf("sum"), soft)
		} else {
			softs[index+1] = monitor.Printer.Sprintf("%8s\t%d", Softirq_name[int32(index)], soft)
		}
	}

	return "\n\n" + strings.Join(softs, "\n")
}
